package com.eduagent.xwqeduagent.api.characterRecognition.UniversalFileRecognition;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONArray;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.List;
import java.util.ArrayList;

/**
 * 讯飞通用OCR大模型客户端
 */
@Slf4j
@Component
public class UniversalFileRecognitionClient {

    private static final String API_URL = "https://cbm01.cn-huabei-1.xf-yun.com/v1/private/se75ocrbm";
    private static final String HOST = "cbm01.cn-huabei-1.xf-yun.com";
    private static final String REQUEST_LINE = "POST /v1/private/se75ocrbm HTTP/1.1";

    @Value("${xunfei.api.text-correction.appid:${xfyun.appid:}}")
    private String appId;

    @Value("${xunfei.api.text-correction.apikey:${xfyun.apikey:}}")
    private String apiKey;

    @Value("${xunfei.api.text-correction.apisecret:${xfyun.apisecret:}}")
    private String apiSecret;
    
    private final HttpClient httpClient;
    
    public UniversalFileRecognitionClient() {
        this.httpClient = HttpClient.newBuilder()
                .version(HttpClient.Version.HTTP_1_1)
                .build();
    }
    
    /**
     * 发送OCR识别请求
     * 
     * @param imageBase64 图片的Base64编码字符串(不包含前缀)
     * @param imageFormat 图片格式（jpg, jpeg, png, bmp）
     * @param uid 用户ID（非必须）
     * @return OCR识别结果
     * @throws IOException 请求异常
     * @throws InterruptedException 请求中断异常
     */
    public UniversalFileRecognitionResult recognize(String imageBase64, String imageFormat, String uid) throws IOException, InterruptedException {
        // 检查图片大小
        byte[] imageBytes = Base64.decodeBase64(imageBase64);
        if (imageBytes.length > 4 * 1024 * 1024) {
            throw new IllegalArgumentException("图片大小不能超过4MB");
        }
        
        // 生成鉴权参数
        String date = getGMTDate();
        String authUrl = getAuthUrl(date);
        
        // 构建请求体
        String requestBody = buildRequestBody(imageBase64, imageFormat, uid);
        
        // 发送HTTP请求
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(authUrl))
                .header("Content-Type", "application/json")
                .header("Date", date)
                .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                .build();
        
        // 发送请求并获取响应
        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
        
        // 检查响应状态码
        int statusCode = response.statusCode();
        if (statusCode != 200) {
            log.error("OCR识别请求失败，状态码：{}，响应：{}", statusCode, response.body());
            throw new IOException("OCR识别请求失败，状态码：" + statusCode);
        }
        
        // 解析响应结果
        return parseResponse(response.body());
    }
    
    /**
     * 构建请求体
     */
    private String buildRequestBody(String imageBase64, String imageFormat, String uid) {
        JSONObject json = new JSONObject();
        
        // header部分
        JSONObject header = new JSONObject();
        header.put("app_id", appId);
        header.put("status", 0);
        if (uid != null && !uid.isEmpty()) {
            header.put("uid", uid);
        }
        json.put("header", header);
        
        // parameter部分
        JSONObject parameter = new JSONObject();
        JSONObject ocr = new JSONObject();
        ocr.put("result_option", "normal");
        ocr.put("result_format", "json");
        ocr.put("output_type", "one_shot");
        ocr.put("exif_option", "0");
        ocr.put("json_element_option", "");
        ocr.put("markdown_element_option", "watermark=0,page_header=0,page_footer=0,page_number=0,graph=0");
        ocr.put("sed_element_option", "watermark=0,page_header=0,page_footer=0,page_number=0,graph=0");
        ocr.put("alpha_option", "0");
        ocr.put("rotation_min_angle", 5);
        
        JSONObject result = new JSONObject();
        result.put("encoding", "utf8");
        result.put("compress", "raw");
        result.put("format", "plain");
        ocr.put("result", result);
        
        parameter.put("ocr", ocr);
        json.put("parameter", parameter);
        
        // payload部分
        JSONObject payload = new JSONObject();
        JSONObject image = new JSONObject();
        image.put("encoding", imageFormat.toLowerCase());
        image.put("image", imageBase64);
        image.put("status", 0);
        image.put("seq", 0);
        payload.put("image", image);
        json.put("payload", payload);
        
        return json.toJSONString();
    }
    
    /**
     * 解析响应结果
     */
    private UniversalFileRecognitionResult parseResponse(String responseBody) {
        log.info("OCR API 响应原始数据: {}", responseBody);
        JSONObject responseJson = JSON.parseObject(responseBody);
        
        // 检查响应码
        JSONObject header = responseJson.getJSONObject("header");
        int code = header.getIntValue("code");
        if (code != 0) {
            String message = header.getString("message");
            log.error("OCR识别服务调用失败，错误码：{}，错误信息：{}", code, message);
            throw new RuntimeException("OCR识别服务调用失败，错误码：" + code + "，错误信息：" + message);
        }
        
        // 获取结果文本
        JSONObject payload = responseJson.getJSONObject("payload");
        if (payload == null || !payload.containsKey("result")) {
            log.error("OCR识别响应格式异常，缺少payload.result字段：{}", responseBody);
            throw new RuntimeException("OCR识别响应格式异常，缺少payload.result字段");
        }
        
        JSONObject result = payload.getJSONObject("result");
        if (result == null || !result.containsKey("text")) {
            log.error("OCR识别响应格式异常，缺少payload.result.text字段：{}", responseBody);
            throw new RuntimeException("OCR识别响应格式异常，缺少payload.result.text字段");
        }
        
        String resultText = result.getString("text");
        log.info("OCR API 响应Base64编码结果: {}", resultText);
        
        if (resultText == null || resultText.isEmpty()) {
            log.warn("OCR识别结果为空");
            return new UniversalFileRecognitionResult(); // 返回空结果
        }
        
        try {
            // Base64解码结果
            String decodedText = new String(Base64.decodeBase64(resultText), StandardCharsets.UTF_8);
            log.info("OCR API 解码后的JSON结果: {}", decodedText);
            
            // 创建识别结果对象
            UniversalFileRecognitionResult recognitionResult = new UniversalFileRecognitionResult();
            
            try {
                // 解析JSON文本结果
                JSONObject jsonResult = JSON.parseObject(decodedText);
                
                // 提取文本内容
                StringBuilder plainText = new StringBuilder();
                
                // 1. 先尝试直接解析success和result结构
                try {
                    if (jsonResult.containsKey("success") && jsonResult.containsKey("result")) {
                        Object resultObj = jsonResult.get("result");
                        if (resultObj instanceof JSONObject) {
                            JSONObject resultObjJson = (JSONObject) resultObj;
                            
                            // 提取content字段
                            if (resultObjJson.containsKey("content")) {
                                String content = resultObjJson.getString("content");
                                if (content != null) {
                                    recognitionResult.setContent(content);
                                }
                            }
                            
                            // 提取plainText字段
                            if (resultObjJson.containsKey("plainText")) {
                                String plainTextStr = resultObjJson.getString("plainText");
                                if (plainTextStr != null) {
                                    plainText.append(plainTextStr);
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    log.warn("解析success/result结构时出现异常: {}", e.getMessage());
                }
                
                // 2. 处理document结构
                try {
                    if (jsonResult.containsKey("document")) {
                        extractTextFromDocumentArray(jsonResult.getJSONArray("document"), plainText);
                    }
                } catch (Exception e) {
                    log.warn("解析document结构时出现异常: {}", e.getMessage());
                }
                
                // 3. 处理image结构
                try {
                    if (jsonResult.containsKey("image")) {
                        extractTextFromImageArray(jsonResult.getJSONArray("image"), plainText);
                    }
                } catch (Exception e) {
                    log.warn("解析image结构时出现异常: {}", e.getMessage());
                }

                // 4. 如果前面的方法没有提取到足够文本，则使用完全递归方法再次尝试
                if (plainText.length() == 0) {
                    try {
                        findAllPossibleText(jsonResult, plainText);
                    } catch (Exception e) {
                        log.warn("使用全文递归方法提取文本时出现异常: {}", e.getMessage());
                    }
                }
                
                // 如果没有找到内容，设置提取的纯文本
                if ((recognitionResult.getContent() == null || recognitionResult.getContent().isEmpty()) && plainText.length() > 0) {
                    recognitionResult.setContent(plainText.toString());
                }
                
                log.info("OCR识别结果对象: content={}, plainText={}",
                    recognitionResult.getContent() != null ? (recognitionResult.getContent().length() > 100 ? 
                        recognitionResult.getContent().substring(0, 100) + "..." : recognitionResult.getContent()) : "null",
                    plainText.length() > 0 ? (plainText.length() > 100 ? plainText.substring(0, 100) + "..." : plainText.toString()) : "空");
                
                return recognitionResult;
            } catch (Exception e) {
                log.warn("高级解析处理失败，尝试直接返回解码后的内容: {}", e.getMessage());
                // 如果 JSON 解析失败，直接返回解码后的文本结果
                recognitionResult.setContent(decodedText);
                return recognitionResult;
            }
        } catch (Exception e) {
            log.error("OCR识别结果解析异常", e);
            throw new RuntimeException("OCR识别结果解析异常: " + e.getMessage(), e);
        }
    }
    
    /**
     * 从document数组中提取文本
     */
    private void extractTextFromDocumentArray(JSONArray documentArray, StringBuilder plainText) {
        if (documentArray == null || documentArray.isEmpty()) {
            return;
        }
        
        for (int i = 0; i < documentArray.size(); i++) {
            Object item = documentArray.get(i);
            if (item instanceof JSONObject) {
                extractTextRecursively((JSONObject) item, plainText);
            }
        }
    }
    
    /**
     * 从image数组中提取文本
     */
    private void extractTextFromImageArray(JSONArray imageArray, StringBuilder plainText) {
        if (imageArray == null || imageArray.isEmpty()) {
            return;
        }
        
        for (int i = 0; i < imageArray.size(); i++) {
            Object item = imageArray.get(i);
            if (item == null || !(item instanceof JSONObject)) {
                continue;
            }
            
            JSONObject imageObj = (JSONObject) item;
            
            // 提取角度信息
            if (imageObj.containsKey("angle")) {
                log.debug("图像角度: {}", imageObj.getFloat("angle"));
            }
            
            // 提取内容
            if (imageObj.containsKey("content")) {
                Object content = imageObj.get("content");
                if (content instanceof JSONArray) {
                    extractContentFromArray((JSONArray) content, plainText);
                }
            }
        }
    }
    
    /**
     * 从content数组中提取文本
     */
    private void extractContentFromArray(JSONArray contentArray, StringBuilder plainText) {
        if (contentArray == null || contentArray.isEmpty()) {
            return;
        }
        
        for (int i = 0; i < contentArray.size(); i++) {
            Object item = contentArray.get(i);
            
            // 确保不是null且是JSONObject类型
            if (item == null || !(item instanceof JSONObject)) {
                continue;
            }
            
            JSONObject contentObj = (JSONObject) item;
            
            // 如果包含category且是text类型，处理其中的文本内容
            if (contentObj.containsKey("category") && "text".equals(contentObj.getString("category"))) {
                if (contentObj.containsKey("content")) {
                    Object content = contentObj.get("content");
                    if (content instanceof JSONArray) {
                        extractContentFromArray(contentObj.getJSONArray("content"), plainText);
                    }
                }
            } 
            // 如果是textblock或text_block类型，提取其中的文本
            else if (contentObj.containsKey("type") && 
                    ("text_block".equals(contentObj.getString("type")) || "textblock".equals(contentObj.getString("type")))) {
                if (contentObj.containsKey("text")) {
                    Object textObj = contentObj.get("text");
                    if (textObj instanceof JSONArray) {
                        for (int j = 0; j < ((JSONArray) textObj).size(); j++) {
                            Object textItem = ((JSONArray) textObj).get(j);
                            if (textItem instanceof String) {
                                if (plainText.length() > 0) {
                                    plainText.append("\n");
                                }
                                plainText.append((String) textItem);
                            }
                        }
                    } else if (textObj instanceof String) {
                        if (plainText.length() > 0) {
                            plainText.append("\n");
                        }
                        plainText.append((String) textObj);
                    }
                }
            }
            // 处理textline类型
            else if (contentObj.containsKey("type") && "textline".equals(contentObj.getString("type"))) {
                if (contentObj.containsKey("text")) {
                    Object textObj = contentObj.get("text");
                    if (textObj instanceof JSONArray) {
                        for (int j = 0; j < ((JSONArray) textObj).size(); j++) {
                            Object textItem = ((JSONArray) textObj).get(j); 
                            if (textItem instanceof String) {
                                if (plainText.length() > 0) {
                                    plainText.append("\n");
                                }
                                plainText.append((String) textItem);
                            }
                        }
                    } else if (textObj instanceof String) {
                        if (plainText.length() > 0) {
                            plainText.append("\n");
                        }
                        plainText.append((String) textObj);
                    }
                }
            }
            // 递归处理嵌套的content
            else if (contentObj.containsKey("content")) {
                Object content = contentObj.get("content");
                if (content instanceof JSONArray) {
                    extractContentFromArray((JSONArray) content, plainText);
                }
            }
            
            // 处理content数组中可能包含的text_unit内容
            if (contentObj.containsKey("content")) {
                Object innerContent = contentObj.get("content");
                if (innerContent instanceof JSONArray) {
                    JSONArray innerArray = (JSONArray) innerContent;
                    for (int j = 0; j < innerArray.size(); j++) {
                        Object innerItem = innerArray.get(j);
                        if (innerItem instanceof JSONObject) {
                            JSONObject innerObj = (JSONObject) innerItem;
                            if (innerObj.containsKey("category") && "text".equals(innerObj.getString("category"))) {
                                extractTextUnit(innerObj, plainText);
                            }
                        }
                    }
                }
            }
        }
    }
    
    /**
     * 提取text_unit内容
     */
    private void extractTextUnit(JSONObject textObj, StringBuilder plainText) {
        if (textObj == null || !textObj.containsKey("content")) {
            return;
        }
        
        Object content = textObj.get("content");
        if (content instanceof JSONArray) {
            JSONArray contentArray = (JSONArray) content;
            for (int i = 0; i < contentArray.size(); i++) {
                Object item = contentArray.get(i);
                if (item instanceof JSONObject) {
                    JSONObject unitObj = (JSONObject) item;
                    if (unitObj.containsKey("text")) {
                        if (plainText.length() > 0) {
                            plainText.append("\n");
                        }
                        plainText.append(unitObj.getString("text"));
                    }
                }
            }
        }
    }
    
    /**
     * 递归提取文本内容
     */
    private void extractTextRecursively(JSONObject json, StringBuilder plainText) {
        if (json == null) {
            return;
        }
        
        // 处理text字段
        if (json.containsKey("text")) {
            Object textValue = json.get("text");
            if (textValue instanceof String) {
                if (!((String) textValue).isEmpty()) {
                    if (plainText.length() > 0) {
                        plainText.append("\n");
                    }
                    plainText.append((String) textValue);
                }
            } else if (textValue instanceof JSONArray) {
                JSONArray textArray = (JSONArray) textValue;
                for (int i = 0; i < textArray.size(); i++) {
                    Object item = textArray.get(i);
                    if (item instanceof String && !((String) item).isEmpty()) {
                        if (plainText.length() > 0) {
                            plainText.append("\n");
                        }
                        plainText.append((String) item);
                    }
                }
            }
        }
        
        // 处理可能包含文本的其他常见字段
        String[] textFieldNames = {"content", "plainText", "plain_text", "text_content", "value"};
        for (String fieldName : textFieldNames) {
            if (json.containsKey(fieldName) && !fieldName.equals("text")) { // text已在上面处理过
                Object value = json.get(fieldName);
                if (value instanceof String && !((String) value).isEmpty()) {
                    if (plainText.length() > 0) {
                        plainText.append("\n");
                    }
                    plainText.append((String) value);
                }
            }
        }
        
        // 递归处理所有字段
        for (String key : json.keySet()) {
            // 跳过已处理的字段
            boolean skipKey = key.equals("text");
            for (String textField : textFieldNames) {
                if (key.equals(textField)) {
                    skipKey = true;
                    break;
                }
            }
            if (skipKey) continue;
            
            Object value = json.get(key);
            
            // 处理嵌套JSON对象
            if (value instanceof JSONObject) {
                extractTextRecursively((JSONObject) value, plainText);
            } 
            // 处理JSON数组
            else if (value instanceof JSONArray) {
                JSONArray array = (JSONArray) value;
                for (int i = 0; i < array.size(); i++) {
                    Object item = array.get(i);
                    if (item instanceof JSONObject) {
                        extractTextRecursively((JSONObject) item, plainText);
                    } else if (item instanceof String && 
                               (key.equals("text") || key.contains("content") || 
                                key.equals("value") || key.contains("text"))) {
                        String textItem = (String) item;
                        if (!textItem.isEmpty()) {
                            if (plainText.length() > 0) {
                                plainText.append("\n");
                            }
                            plainText.append(textItem);
                        }
                    }
                }
            }
        }
    }
    
    /**
     * 查找所有可能的文本内容，更积极地从JSON中提取文本
     */
    private void findAllPossibleText(JSONObject json, StringBuilder plainText) {
        if (json == null) return;
        
        // 遍历所有字段，查找可能包含文本的内容
        for (String key : json.keySet()) {
            Object value = json.get(key);
            
            // 如果是字符串值且看起来像文本内容，则添加
            if (value instanceof String) {
                String strValue = (String) value;
                if (isTextContent(strValue, key)) {
                    if (plainText.length() > 0) plainText.append("\n");
                    plainText.append(strValue);
                }
            } 
            // 递归处理JSON对象
            else if (value instanceof JSONObject) {
                findAllPossibleText((JSONObject) value, plainText);
            }
            // 处理数组
            else if (value instanceof JSONArray) {
                JSONArray array = (JSONArray) value;
                for (int i = 0; i < array.size(); i++) {
                    Object item = array.get(i);
                    if (item instanceof JSONObject) {
                        findAllPossibleText((JSONObject) item, plainText);
                    } else if (item instanceof String) {
                        String strItem = (String) item;
                        if (isTextContent(strItem, key)) {
                            if (plainText.length() > 0) plainText.append("\n");
                            plainText.append(strItem);
                        }
                    }
                }
            }
        }
    }
    
    /**
     * 判断一个字符串是否像是文本内容
     */
    private boolean isTextContent(String str, String fieldName) {
        if (str == null || str.isEmpty()) return false;
        
        // 看起来像文本字段的字段名
        String[] textFieldPrefixes = {"text", "content", "value", "title", "desc", "info"};
        for (String prefix : textFieldPrefixes) {
            if (fieldName.toLowerCase().contains(prefix)) {
                return true;
            }
        }
        
        // 如果字符串比较长且包含空格，可能是句子
        if (str.length() > 10 && str.contains(" ")) {
            return true;
        }
        
        // 如果字符串包含汉字
        if (containsChinese(str) && str.length() > 2) {
            return true;
        }
        
        return false;
    }
    
    /**
     * 检查字符串是否包含汉字
     */
    private boolean containsChinese(String str) {
        for (char c : str.toCharArray()) {
            if (c >= '\u4e00' && c <= '\u9fa5') { // 汉字的Unicode范围
                return true;
            }
        }
        return false;
    }
    
    /**
     * 获取GMT格式的日期字符串
     */
    private String getGMTDate() {
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        return format.format(new Date());
    }
    
    /**
     * 生成鉴权URL
     */
    private String getAuthUrl(String date) {
        try {
            // 构建鉴权原始字符串
            String signatureOrigin = "host: " + HOST + "\n" +
                    "date: " + date + "\n" +
                    REQUEST_LINE;
            
            // 使用HMAC-SHA256算法生成签名
            Mac hmacSha256 = Mac.getInstance("HmacSHA256");
            hmacSha256.init(new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
            byte[] signatureSha = hmacSha256.doFinal(signatureOrigin.getBytes(StandardCharsets.UTF_8));
            String signature = Base64.encodeBase64String(signatureSha);
            
            // 构建authorization参数原始字符串
            String authorizationOrigin = "api_key=\"" + apiKey + "\", algorithm=\"hmac-sha256\", headers=\"host date request-line\", signature=\"" + signature + "\"";
            
            // Base64编码
            String authorization = Base64.encodeBase64String(authorizationOrigin.getBytes(StandardCharsets.UTF_8));
            
            // URL编码date参数
            String encodedDate = URLEncoder.encode(date, StandardCharsets.UTF_8.toString());
            
            // 拼接最终URL
            return API_URL + "?authorization=" + authorization +
                    "&host=" + HOST +
                    "&date=" + encodedDate;
            
        } catch (NoSuchAlgorithmException | InvalidKeyException | IOException e) {
            log.error("生成鉴权URL失败", e);
            throw new RuntimeException("生成鉴权URL失败", e);
        }
    }

    /**
     * 发送OCR识别请求（带高级参数）
     * 
     * @param request 包含高级参数的请求对象
     * @return OCR识别结果
     * @throws IOException 请求异常
     * @throws InterruptedException 请求中断异常
     */
    public UniversalFileRecognitionResult recognizeWithAdvancedOptions(Base64RecognitionRequest request) throws IOException, InterruptedException {
        // 检查图片大小
        byte[] imageBytes = Base64.decodeBase64(request.getBase64Content());
        if (imageBytes.length > 4 * 1024 * 1024) {
            throw new IllegalArgumentException("图片大小不能超过4MB");
        }
        
        // 生成鉴权参数
        String date = getGMTDate();
        String authUrl = getAuthUrl(date);
        
        // 构建请求体
        String requestBody = buildAdvancedRequestBody(request);
        
        // 发送HTTP请求
        HttpRequest httpRequest = HttpRequest.newBuilder()
                .uri(URI.create(authUrl))
                .header("Content-Type", "application/json")
                .header("Date", date)
                .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                .build();
        
        // 发送请求并获取响应
        HttpResponse<String> response = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
        
        // 检查响应状态码
        int statusCode = response.statusCode();
        if (statusCode != 200) {
            log.error("OCR识别请求失败，状态码：{}，响应：{}", statusCode, response.body());
            throw new IOException("OCR识别请求失败，状态码：" + statusCode);
        }
        
        // 解析响应结果
        return parseResponse(response.body());
    }
    
    /**
     * 构建高级请求体
     */
    private String buildAdvancedRequestBody(Base64RecognitionRequest request) {
        JSONObject json = new JSONObject();
        
        // header部分
        JSONObject header = new JSONObject();
        header.put("app_id", appId);
        header.put("status", 0);
        if (request.getUid() != null && !request.getUid().isEmpty()) {
            header.put("uid", request.getUid());
        }
        // 添加请求ID
        header.put("request_id", java.util.UUID.randomUUID().toString());
        json.put("header", header);
        
        // parameter部分
        JSONObject parameter = new JSONObject();
        JSONObject ocr = new JSONObject();
        
        // 设置高级参数
        ocr.put("result_option", request.getResultOption() != null ? request.getResultOption() : "normal");
        
        // 设置result_format参数，确保使用有效的值
        String resultFormat = "json"; // 默认值
        if (request.getResultFormat() != null) {
            // 获取用户请求的结果格式
            String requestedFormat = request.getResultFormat();
            
            // 检查请求的格式是否在允许的列表中
            String[] allowedFormats = {
                "json", 
                "json,markdown", 
                "json,sed", 
                "json,markdown,sed", 
                "json,markdown,sed,word"
            };
            
            boolean isValidFormat = false;
            for (String allowedFormat : allowedFormats) {
                if (allowedFormat.equals(requestedFormat)) {
                    resultFormat = requestedFormat;
                    isValidFormat = true;
                    break;
                }
            }
            
            if (!isValidFormat) {
                log.warn("请求的result_format值'{}' 无效，使用默认值'json'", requestedFormat);
            }
        }
        ocr.put("result_format", resultFormat);
        
        ocr.put("output_type", request.getOutputType() != null ? request.getOutputType() : "one_shot");
        ocr.put("exif_option", request.getExifOption() != null ? request.getExifOption() : "0");
        ocr.put("json_element_option", "");
        
        // 元素选项
        String markdownOption = request.getMarkdownElementOption() != null ? 
                request.getMarkdownElementOption() : 
                "watermark=0,page_header=0,page_footer=0,page_number=0,graph=0";
        ocr.put("markdown_element_option", markdownOption);
        
        String sedOption = request.getSedElementOption() != null ? 
                request.getSedElementOption() : 
                "watermark=0,page_header=0,page_footer=0,page_number=0,graph=0";
        ocr.put("sed_element_option", sedOption);
        
        ocr.put("alpha_option", request.getAlphaOption() != null ? request.getAlphaOption() : "0");
        ocr.put("rotation_min_angle", request.getRotationMinAngle() != null ? request.getRotationMinAngle() : 5);
        
        JSONObject result = new JSONObject();
        result.put("encoding", "utf8");
        result.put("compress", "raw");
        result.put("format", "plain");
        ocr.put("result", result);
        
        parameter.put("ocr", ocr);
        json.put("parameter", parameter);
        
        // payload部分
        JSONObject payload = new JSONObject();
        JSONObject image = new JSONObject();
        image.put("encoding", request.getImageFormat().toLowerCase());
        image.put("image", request.getBase64Content());
        image.put("status", 0);
        image.put("seq", 0);
        payload.put("image", image);
        json.put("payload", payload);
        
        return json.toJSONString();
    }
} 